package com.qinghua.blog.service;

import com.qinghua.blog.NoFoundException;
import com.qinghua.blog.dao.BlogRepository;
import com.qinghua.blog.po.Blog;
import com.qinghua.blog.po.Type;
import com.qinghua.blog.util.MarkdownUtils;
import com.qinghua.blog.util.MyBeanUtils;
import com.qinghua.blog.vo.BlogQuery;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.util.*;

@Service
public class BlogServiceImpl implements BlogService{

    @Autowired
    BlogRepository blogRepository;

    @Transactional
    @Override
    public Blog getBlog(Long id) {
        System.out.println(id);
        Blog blog=blogRepository.getOne(id);
        return blog;
    }

    @Transactional
    @Override
    public Page<Blog> listBlog(Pageable pageable, BlogQuery blogQuery) {

        return blogRepository.findAll(new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                List<Predicate> predicates=new ArrayList<>();
                if(!"".equals(blogQuery.getTitle()) && blogQuery.getTitle()!=null){
                    predicates.add(cb.like(root.<String>get("title"),"%"+blogQuery.getTitle()+"%"));
                }
                if((blogQuery.getTypeId())!=null){
                    predicates.add(cb.equal(root.<Type>get("type").get("id"),blogQuery.getTypeId()));
                }
                if(blogQuery.isRecommend()){
                    predicates.add(cb.equal(root.<Boolean>get("recommend"),blogQuery.isRecommend()));
                }
                cq.where(predicates.toArray(new Predicate[predicates.size()]));
                return null;
            }
        },pageable);
    }

    @Transactional
    @Override
    public Page<Blog> listBlog(Pageable pageable) {

        return blogRepository.findAll(pageable);
    }

    //根据标签id查询所有对应的博客
    @Override
    public Page<Blog> listBlog(Long id, Pageable pageable) {

        return blogRepository.findAll(new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                Join join=root.join("tags");
                return cb.equal(join.get("id"),id);
            }
        },pageable);
    }

    @Override
    public Map<String,List<Blog>> archiveBlog() {
        List<String> years=blogRepository.findGroupTear();
        Map<String,List<Blog>> map= new HashMap<>();
        for(String year:years){
            map.put(year,blogRepository.findByYear(year));
        }
        return map;
    }

    @Override
    public Long countBlog() {
        return blogRepository.count();
    }

    @Transactional(readOnly = true)
    @Override
    public Blog getConvertBlog(Long id) {
        Blog blog=blogRepository.getOne(id);

        if(blog==null){
            throw new NoFoundException("博客不存在");
        }
        Blog b=new Blog();
        BeanUtils.copyProperties(blog,b);
        String content=b.getContent();
        b.setContent(MarkdownUtils.markdownToHtmlExtensions(content));
        return b;
    }

    @Transactional
    @Override
    public Page<Blog> listBlog(String query, Pageable pageable) {

        return blogRepository.findByQuery(query,pageable);
    }

    @Transactional
    @Override
    public List<Blog> findByTop(Integer size) {
        Sort sort=Sort.by(Sort.Direction.DESC,"updateTime");
        Pageable pageable=PageRequest.of(0,size,sort);
        return blogRepository.findByTop(pageable);
    }

    @Transactional
    @Override
    public Blog saveBlog(Blog blog) {
        if(blog.getId()==null){
            blog.setUpdateTime(new Date());
            blog.setCreateTime(new Date());
        }else {
            blog.setUpdateTime(new Date());
        }
        return blogRepository.save(blog);
    }

    @Transactional
    @Override
    public Blog updateBlog(Long id, Blog blog) {
      Blog b=blogRepository.getOne(id);
        if(b!=null){
            BeanUtils.copyProperties(blog,b, MyBeanUtils.getNullPropertyNames(blog));
            return blogRepository.save(b);
        }else {
            throw new NoFoundException();
        }
    }

    @Transactional
    @Override
    public void deleteBlog(Long id) {

        blogRepository.deleteById(id);

    }
}
